package com.haohuo.wrapper;

import org.slf4j.MDC;

import java.util.Map;

/**
 * @Author: pk.zhang
 * @Date: 2021/3/12 11:01
 */
public class MDCRunnable implements Runnable {


    private Runnable runnable;

    /**
     * 保存当前主线程的MDC值
     */
    private final Map<String, String> mainMdcMap;

    // 初始化对象实现mdc复制
    public MDCRunnable(Runnable runnable) {
        this.runnable = runnable;
        this.mainMdcMap = MDC.getCopyOfContextMap();
    }

    @Override
    public void run() {
        // 将父线程的MDC值赋给子线程
        for (Map.Entry<String, String> entry : mainMdcMap.entrySet()) {
            MDC.put(entry.getKey(), entry.getValue());
        }
        // 执行被装饰的线程run方法
        try {
            runnable.run();
        } finally {
            // 执行结束移除MDC值
            MDC.clear();
        }
    }
}
